package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.controller.form.*;
import com.woniuxy.controller.info.*;
import com.woniuxy.dao.*;
import com.woniuxy.model.*;
import com.woniuxy.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.utils.CopyUtil;
import com.woniuxy.utils.MyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 马世亮
 * @since 2022-02-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Resource
    private UserDao userDao;
    @Resource
    private AccountDao accountDao;
    @Resource
    private AccountRoleDao accountRoleDao;
    @Resource
    private ProjectRoleUserDao projectRoleUserDao;
    @Resource
    private ProjectRoleDao projectRoleDao;


    @Override
    public List<UserAndRoleInfo> getUsers(ProjectIdForm projectIdForm) {

        List<User> users = userDao.getUserNorole(projectIdForm.getPid());

        List<UserAndRoleInfo> list = CopyUtil.copyList(users, UserAndRoleInfo.class);

        return list;
    }

    @Override
    public boolean giveUserRole(UserNewRoleForm userNewRoleForm) throws MyException {
        System.out.println(userNewRoleForm);
        ProjectRole projectRole = projectRoleDao.selectOne(new QueryWrapper<ProjectRole>().eq("project_role_id", userNewRoleForm.getRoleid()));
        System.out.println(projectRole);
        String s = "";
        for (int i = 0; i < userNewRoleForm.getUserids().size(); i++) {
            if(i<userNewRoleForm.getUserids().size()-1) {s+=(userNewRoleForm.getUserids().get(i)+",");}
            else{ s+=userNewRoleForm.getUserids().get(i); }
        }

        List<User> users = userDao.selectBatchIds(userNewRoleForm.getUserids());
        ArrayList<Integer> aids = new ArrayList<>();
        for (User user : users) {
            aids.add(user.getAccountId());
        }
        List<AccountRole> accountRoles = accountRoleDao.selectList(new QueryWrapper<AccountRole>().in("account_id",aids));
        if(projectRole.getSystemSign().equals("产品经理")){
            for (AccountRole accountRole : accountRoles) {
                if (accountRole.getRoleId()!=2) {
                    throw new MyException(500,"该项目角色仅可经理胜任");
                }
            }
        }else {
            for (AccountRole accountRole : accountRoles) {
                if (accountRole.getRoleId()!=3) {
                    throw new MyException(500,"该项目角色仅可员工胜任");
                }
            }
        }

        Integer updateuser= userDao.updateuser(s);
        if(updateuser <= 0) return false;
        System.out.println(s+","+updateuser);

        String pru = "";
        for (int i = 0; i < userNewRoleForm.getUserids().size(); i++) {
            if(i<userNewRoleForm.getUserids().size()-1) {
                pru+=("(DEFAULT,"+userNewRoleForm.getRoleid()+","+userNewRoleForm.getProjectid()+","+userNewRoleForm.getUserids().get(i)+"),");
            }
            else{
                pru+=("(DEFAULT,"+userNewRoleForm.getRoleid()+","+userNewRoleForm.getProjectid()+","+userNewRoleForm.getUserids().get(i)+")");
            }
        }
        System.out.println(pru);
        Integer b  = projectRoleUserDao.insertmany(pru);
        if(b<=0) return false;
        return true;
    }

    @Override
    public IPage<UserAndRolesInfo> getUserAndRole(ProjectIdForm projectIdForm) {

        Page<UserAndRolesInfo> liPage = new Page<>(projectIdForm.getPagenum() == 0 ? 1 : projectIdForm.getPagenum(), projectIdForm.getPagesize() == 0 ? 10 : projectIdForm.getPagesize());


        IPage<UserAndRolesInfo> userAndRole = userDao.getUserAndRole(projectIdForm.getPid(), liPage);

        Page<UserAndRolesInfo> liInfoPage = new Page<>();
        liInfoPage.setCurrent(liPage.getCurrent());
        liInfoPage.setRecords(userAndRole.getRecords());
        liInfoPage.setSize(liPage.getSize());
        liInfoPage.setTotal(liPage.getTotal());
        return liInfoPage;
    }

    @Override
    public boolean removerole(UserRoleForm userRoleForm) {

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("u_id",userRoleForm.getUId());

        User user = userDao.selectOne(wrapper);
        Integer uState = user.getUState();
        user.setUState(uState-1);
        int update = userDao.update(user, wrapper);
        if(update<=0) return false;

        QueryWrapper<ProjectRoleUser> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("u_id",userRoleForm.getUId()).eq("project_role_id",userRoleForm.getProjectRoleId());
        int delete = projectRoleUserDao.delete(wrapper1);
        return delete>0? true:false;
    }

    @Override
    public List<User> getuserByinfo(String userinfo) {

        return userDao.getUserByinfo(userinfo);
    }

    @Override
    public boolean addnewuser(NewuserForm newuserForm) throws MyException{

        Account username = accountDao.selectOne(new QueryWrapper<Account>().eq("username", newuserForm.getAccount()));
        System.out.println(username);
        if(null != username) throw new MyException(500,"账户已存在，请重新输入");

        Account account = new Account();
        account.setUsername(newuserForm.getAccount());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        account.setPassword(encoder.encode(newuserForm.getPsw()));
        int insert = accountDao.insert(account);
        if(insert <= 0) throw new MyException(500,"账号添加失败，请稍后重试");

        User user = new User();
        user.setAccountId(account.getAId());
        user.setAccountUsername(newuserForm.getAccount());
        user.setUName(newuserForm.getUname());
        user.setUGender(newuserForm.getUgen());
        user.setUTel(newuserForm.getUtel());
        user.setUEmail(newuserForm.getUemail());
        user.setProjectRoleId(0);
        user.setUDelect(0);

        int insert1 = userDao.insert(user);
        if(insert>0) return true;
        return false;
    }

    @Override
    public IPage<UserAndAccountInfo> getAllusers(PageForm pageForm) {

        Page<UserAndAccountInfo> liPage = new Page<>(pageForm.getPagenum() == 0 ? 1 : pageForm.getPagenum(), pageForm.getPagesize() == 0 ? 10 : pageForm.getPagesize());

        IPage<UserAndAccountInfo> allusers = userDao.getAllusers(liPage);
        List<UserAndAccountInfo> records = allusers.getRecords();
        System.out.println(records);
        for (UserAndAccountInfo record : records) {
            if(null == record.getRoleName()|| record.getRoleName().equals("")){
                record.setRoleName("未授权");
            }
        }

        Page<UserAndAccountInfo> liInfoPage = new Page<>();
        liInfoPage.setCurrent(liPage.getCurrent());
        liInfoPage.setRecords(records);
        liInfoPage.setSize(liPage.getSize());
        liInfoPage.setTotal(liPage.getTotal());
        return liInfoPage;
    }

    @Override
    public boolean changeuser(UserChangeForm userChangeForm) throws MyException {

        Account account = new Account();
        account.setUsername(userChangeForm.getAccountUsername());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        account.setPassword(encoder.encode(userChangeForm.getPsw()));
        int update = accountDao.update(account, new QueryWrapper<Account>().eq("", userChangeForm.getAccountId()));
        if(update<=0) throw new MyException(500,"用户修改失败，请稍后重试");

        if(account.getUsername() != userChangeForm.getAccountUsername()){
            Account username = accountDao.selectOne(new QueryWrapper<Account>().eq("username", userChangeForm.getAccountUsername()));
            if(null != username) throw new MyException(500,"账号已存在，请重新输入");
        }

        User user = new User();
        user.setAccountUsername(userChangeForm.getAccountUsername());
        user.setUName(userChangeForm.getUName());
        user.setUGender(userChangeForm.getUGender());
        user.setUTel(userChangeForm.getUTel());
        user.setUEmail(userChangeForm.getUEmail());
        int uId = userDao.update(user, new QueryWrapper<User>().eq("u_id", userChangeForm.getUId()));

        return uId>0? true:false;
    }

    @Override
    public boolean removeuser(UserAndAccountInfo userAndAccountInfo) throws MyException {

        int aId = accountDao.delete(new QueryWrapper<Account>().eq("a_id", userAndAccountInfo.getAccountId()));
        if(aId <= 0) throw new MyException(500,"账号清除失败，请稍后重试");

        int delete = userDao.delete(new QueryWrapper<User>().eq("u_id", userAndAccountInfo.getUId()).eq("account_id", userAndAccountInfo.getAccountId()));
        if( delete<=0) return false;

        int acconutId = accountRoleDao.delete(new QueryWrapper<AccountRole>().eq("account_id", userAndAccountInfo.getAccountId()));
        return true;
    }

    @Override
    public boolean removemany(UserManyForm userManyForm) throws MyException {

        List<Integer> accountids = new ArrayList<>();
        for (UserAndAccountInfo userAndAccountInfo : userManyForm.getList()) {
            accountids.add(userAndAccountInfo.getAccountId());
        }
        List<Integer> uids = new ArrayList<>();
        for (UserAndAccountInfo userAndAccountInfo : userManyForm.getList()) {
            uids.add(userAndAccountInfo.getUId());
        }

        int aId = accountDao.delete(new QueryWrapper<Account>().in("a_id",accountids));
        if(aId <= 0) throw new MyException(500,"账号清除失败，请稍后重试");

        int delete = userDao.delete(new QueryWrapper<User>().in("u_id", uids).in("account_id",accountids));
        if( delete<=0) return false;
        int acconutId = accountRoleDao.delete(new QueryWrapper<AccountRole>().in("account_id", accountids));

        //if(acconutId <= 0) throw new MyException(500,"解除权限失败，请好后重试");
        return true;
    }

    @Override
    public RoleModel ismanager(Integer uid) {

        List<Project> list = null;
        RoleModel ornotManager = userDao.isOrnotManager(uid);

        return ornotManager;
    }

    @Override
    public List<UserAndRolesInfo> getHasroleUser(Integer pid) {

        List<UserAndRolesInfo> hasRoleUser = userDao.getHasRoleUser(pid);
        return hasRoleUser;
    }

    @Override
    public boolean changeuserrole(UserNewRoleForm userNewRoleForm) throws MyException {

        ProjectRole projectRole = projectRoleDao.selectOne(new QueryWrapper<ProjectRole>().eq("project_role_id", userNewRoleForm.getRoleid()));

        String s = "";
        for (int i = 0; i < userNewRoleForm.getUserids().size(); i++) {
            if(i<userNewRoleForm.getUserids().size()-1) {s+=(userNewRoleForm.getUserids().get(i)+",");}
            else{ s+=userNewRoleForm.getUserids().get(i); }
        }

        List<User> users = userDao.selectBatchIds(userNewRoleForm.getUserids());
        ArrayList<Integer> aids = new ArrayList<>();
        for (User user : users) {
            aids.add(user.getAccountId());
        }
        List<AccountRole> accountRoles = accountRoleDao.selectList(new QueryWrapper<AccountRole>().in("account_id",aids));
        if(projectRole.getSystemSign().equals("产品经理")){
            for (AccountRole accountRole : accountRoles) {
                if (accountRole.getRoleId()!=2) {
                    throw new MyException(500,"该项目角色仅可经理胜任");
                }
            }
        }else {
            for (AccountRole accountRole : accountRoles) {
                if (accountRole.getRoleId()!=3) {
                    throw new MyException(500,"该项目角色仅可员工胜任");
                }
            }
        }

        ProjectRoleUser projectRoleUser = new ProjectRoleUser();
        projectRoleUser.setProjectRoleId(userNewRoleForm.getRoleid());

        QueryWrapper<ProjectRoleUser> wrapper = new QueryWrapper<>();
        wrapper.in("u_id",userNewRoleForm.getUserids()).eq("project_id",userNewRoleForm.getProjectid());

        int up = projectRoleUserDao.update(projectRoleUser, wrapper);

        return up>0? true:false;
    }


}
